from .service import ServiceState
import curses


def draw_frame(scr, services):
    for service in services:
        _draw_service_line(scr, service)


def _draw_state(scr, state):
    pairs = {
        ServiceState.UP: curses.COLOR_GREEN,
        ServiceState.DOWN: curses.COLOR_RED,
        ServiceState.STARTING: curses.COLOR_YELLOW,
        ServiceState.STOPPING: curses.COLOR_YELLOW,
        ServiceState.UNKNOWN: curses.COLOR_YELLOW,
        }

    for pair in pairs.items():
        curses.init_pair(pair[0].value, pair[1], -1)

    if state == ServiceState.UP:
        scr.addstr('  UP  ', curses.color_pair(state.value))

    elif state == ServiceState.DOWN:
        scr.addstr(' DOWN ', curses.color_pair(state.value))

    elif state == ServiceState.STARTING:
        decoration = curses.A_BLINK | curses.A_BOLD
        scr.addstr('^', curses.color_pair(state.value) | decoration)
        scr.addstr('DOWN', curses.color_pair(ServiceState.DOWN.value))
        scr.addstr('^', curses.color_pair(state.value) | decoration)

    elif state == ServiceState.STOPPING:
        decoration = curses.A_BLINK | curses.A_BOLD
        scr.addstr('v ', curses.color_pair(state.value) | decoration)
        scr.addstr('UP', curses.color_pair(ServiceState.UP.value))
        scr.addstr(' v', curses.color_pair(state.value) | decoration)

    elif state == ServiceState.UNKNOWN:
        scr.addstr('  ??  ', curses.color_pair(state.value))

    else:
        pass  # unreachable


def _draw_branch(scr, service):
    curses.init_pair(1, curses.COLOR_GREEN, -1)
    scr.addstr('<%s>' % service.branch, curses.color_pair(1))


def _draw_service_line(scr, service):
    curses.init_pair(6, curses.COLOR_CYAN, -1)
    scr.addstr('(%s) ' % service.tag, curses.color_pair(6))
    scr.addstr('[')
    _draw_state(scr, service.state)
    scr.addstr('] ')
    scr.addstr(service.name)
    scr.addstr(' ')
    _draw_branch(scr, service)
    scr.addstr('\n')
